package com.sm.li.service.base.impl;

import com.baomidou.mybatisplus.core.conditions.AbstractLambdaWrapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sm.li.entity.Brand;
import com.sm.li.entity.Menu;
import com.sm.li.entity.base.BaseEntity;
import com.sm.li.mapper.base.MyBaseMapper;
import com.sm.li.service.base.BaseService;
import com.sm.li.utils.ReflectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

public class BaseServiceImpl<T> implements BaseService<T> {

    @Autowired
    private MyBaseMapper<T> myBaseMapper;

    @Override
    public List<T> list() {
        return myBaseMapper.selectList(null);
    }

//    @Override
//    public List<T> search(LambdaQueryWrapper<T> queryWrapper) {
//        return myBaseMapper.selectList(queryWrapper);
//    }

    @Override
    public T findById(Long id) {
        return myBaseMapper.selectById(id);
    }

    @Override
    public int add(T t) {
        //第一种方式（强转）
//        BaseEntity baseEntity= (BaseEntity) t;
//        baseEntity.setData();
        //第二种方式（反射工具类）
        ReflectionUtils.invokeMethod(t,"setData",null,null);
        return myBaseMapper.insert(t);
    }

    @Override
    public int update(T t) {
        //第二种方式（反射工具类）
        ReflectionUtils.invokeMethod(t,"setData",null,null);
        return myBaseMapper.updateById(t);
    }

    @Override
    public int deleteById(Long id) {
        return myBaseMapper.deleteById(id);
    }

    @Transactional
    @Override
    public int deleteBatchIds(List<Long> ids) {
        return myBaseMapper.deleteBatchIds(ids);
    }

    @Override
    public void getCascadeChildrenIds(Long id, List<Long> ids) {
        List<T> ts = myBaseMapper.selectList(new QueryWrapper<T>().eq("parent_id", id));
        if (!CollectionUtils.isEmpty(ts)) {
            ts.forEach(t -> {
                ids.add((Long) ReflectionUtils.getFieldValue(t, "id"));
                getCascadeChildrenIds((Long)ReflectionUtils.getFieldValue(t,"id"),ids);
            });
        }
    }
}
